package cn.ztf.zshop.service.impl;

import cn.ztf.zshop.bean.dto.AreaVo;
import cn.ztf.zshop.bean.po.Area;
import cn.ztf.zshop.bean.vo.AreaDto;
import cn.ztf.zshop.common.exception.ZShopException;
import cn.ztf.zshop.dao.AreaDao;
import cn.ztf.zshop.service.AreaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class AreaServiceImpl extends ServiceImpl<AreaDao, Area> implements AreaService {

    @Autowired
    private MapperFacade mapperFacade;

    /**
     * map 优化 树结构
     * @return
     */
    @Override
    public List<AreaVo> listArea() {
        List<Area> selectList = baseMapper.selectList(null);
        HashMap<Long, AreaVo> map = new HashMap<>();
        for (Area area : selectList) {
            AreaVo dto = mapperFacade.map(area, AreaVo.class);
            map.put(dto.getAreaId(),dto);
        }
        List<AreaVo> linkedList = new LinkedList<>();
        for (AreaVo dto : map.values()) {
            AreaVo parent = map.get(dto.getParentId());
            if (ObjectUtils.isEmpty(parent)){
                linkedList.add(dto);
            }else {
                List<AreaVo> areaVoList =parent.getChildren();
                if (ObjectUtils.isEmpty(areaVoList)) {
                    areaVoList = new LinkedList<>();
                    parent.setChildren(areaVoList);
                }
                areaVoList.add(dto);
            }
        }
        return linkedList;
    }

    @Override
    public void add(AreaDto areaDto) {
        Area area = mapperFacade.map(areaDto, Area.class);
        baseMapper.insert(area);
    }

    @Override
    public void update(AreaDto areaDto) {
        Area area = mapperFacade.map(areaDto, Area.class);
        baseMapper.updateById(area);
    }

    @Override
    public AreaVo getAreaById(Long areaId) {
        Area area = baseMapper.selectById(areaId);
        AreaVo areaVo = mapperFacade.map(area, AreaVo.class);
        return areaVo;
    }

    @Override
    public void deleteAreaById(Long id) {
        LambdaQueryWrapper<Area> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Area::getParentId,id);
        Long count = baseMapper.selectCount(wrapper);
        if (count>0){
            // 无法删除非叶子节点
            throw new ZShopException("无法删除非根节点数据");
        }
        baseMapper.deleteById(id);
    }
}
